package com.example.demo.service.impl;

import com.example.demo.entity.User;
import com.example.demo.entity.UserStats;
import com.example.demo.mapper.UserMapper;
import com.example.demo.mapper.UserStatsMapper;
import com.example.demo.service.UserStatsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

/**
 * 用户统计服务实现类
 * 实现用户统计相关的业务逻辑
 */
@Service
public class UserStatsServiceImpl implements UserStatsService {
    
    private static final Logger log = LoggerFactory.getLogger(UserStatsServiceImpl.class);
    
    private final UserStatsMapper userStatsMapper;
    private final UserMapper userMapper;
    
    /**
     * 构造器注入
     * @param userStatsMapper 用户统计Mapper
     * @param userMapper 用户Mapper
     */
    public UserStatsServiceImpl(UserStatsMapper userStatsMapper, UserMapper userMapper) {
        this.userStatsMapper = userStatsMapper;
        this.userMapper = userMapper;
    }
    
    @Override
    public UserStats getUserStats(Long userId) {
        UserStats stats = userStatsMapper.selectByUserId(userId);
        
        // 如果统计记录不存在，创建一个默认记录
        if (stats == null) {
            log.info("用户{}的统计记录不存在，创建默认统计记录", userId);
            stats = createUserStats(userId);
        }
        
        return stats;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserStats createUserStats(Long userId) {
        log.info("为用户{}创建统计记录", userId);
        
        UserStats stats = new UserStats();
        stats.setUserId(userId);
        stats.setLoginCount(0);
        stats.setTotalOnlineTime(0L);
        stats.setCreateTime(LocalDateTime.now());
        stats.setUpdateTime(LocalDateTime.now());
        
        int rows = userStatsMapper.insert(stats);
        if (rows == 1) {
            log.info("用户{}统计记录创建成功", userId);
        } else {
            log.error("用户{}统计记录创建失败", userId);
        }
        
        return stats;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recordLogin(Long userId) {
        log.info("记录用户{}登录", userId);
        
        // 检查统计记录是否存在，不存在则创建
        UserStats existingStats = userStatsMapper.selectByUserId(userId);
        if (existingStats == null) {
            createUserStats(userId);
        }
        
        // 更新登录统计
        int rows = userStatsMapper.updateLoginStats(userId);
        if (rows == 1) {
            log.info("用户{}登录统计更新成功", userId);
        } else {
            log.error("用户{}登录统计更新失败", userId);
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recordLogout(Long userId, Long onlineMinutes) {
        log.info("记录用户{}登出，在线时长：{}分钟", userId, onlineMinutes);
        
        // 更新登出时间
        userStatsMapper.updateLogoutTime(userId);
        
        // 如果提供了在线时长，则更新总在线时长
        if (onlineMinutes != null && onlineMinutes > 0) {
            userStatsMapper.updateOnlineTime(userId, onlineMinutes);
        }
        
        log.info("用户{}登出统计更新成功", userId);
    }
    
    @Override
    public Long calculateAccountAge(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null || user.getCreateTime() == null) {
            return 0L;
        }
        
        // 计算注册时间到现在的天数
        LocalDateTime createTime = user.getCreateTime();
        LocalDateTime now = LocalDateTime.now();
        long days = ChronoUnit.DAYS.between(createTime, now);
        
        // 至少显示1天
        return Math.max(1, days);
    }
}
